<?php 
//there was a problem entering the services hours into the MISRservices table
//with the inital INSERT query.  this error only occured when the user created
//a new case note record.  i fixed that on 11-20-08

	session_start();
	
	//FOR DEBUGGING--comment out when done!
	ini_set('display_errors', 1);
	ini_set('error_reporting', E_ALL ^ E_NOTICE);
	error_reporting(1);
	//include('../includes/phpheader.php');
	include('../includes/db_connect.php'); 
	//consumer ID
	$id = $_POST["id"];
	
	
	//casenote ID
	$isrId = $_POST["isrId"];
	if(!$isrId) {
		$isrId="0";
	}
	
	
	//I&R ID
	#i have this here in case the coordinator
	#needs to create a consumer ir 
	$irId = $_POST["irId"];
	if(!$irId) {
		$irId="0";
	}
	//coordinator id
	$userId = $_SESSION['user_id'];
	$caseNoteMonth = $_POST["caseNoteMonth"];
	$caseNoteYear = $_POST["caseNoteYear"];
	$caseNoteCoordinator = $_POST["caseNoteCoordinator"];
	$serviceType = $_POST["serviceType"];
	$totalServiceContacts = $_POST["totalServiceContacts"];
	if(!$totalServiceContacts) {
		$totalServiceContacts="0";
	}
	$contactByPerson = $_POST["contactByPerson"];
	$contactByPhone = $_POST["contactByPhone"];
	$contactByMail = $_POST["contactByMail"];

	if(!$contactByPerson) $contactByPerson=0; else $contactByPerson=1;
	if(!$contactByPhone) 	$contactByPhone=0; else 	$contactByPhone=1;
	if(!$contactByMail) $contactByMail=0; else $contactByMail=1;

	$services = $_POST["services"];
	if(!$services) {
		$services="0";
	}
	
	$serviceHourTotals = $_POST["serviceHourTotals"];

	#let's look for an existing record
	$query = "SELECT id 
				FROM monthlyISR 
				WHERE consumer_id = ".$id." 
				AND id = ".$isrId;


if(mysql_fetch_array(mysql_query($query))) {
	
	//we found a record, so update it
	$query = "UPDATE `monthlyISR` 
			      SET 	`ir_id` = ".$irId.", 
					`case_note_month` = '".$caseNoteMonth."', 
					`case_note_year` = '".$caseNoteYear."',
					`case_note_coordinator` = '".$caseNoteCoordinator."',	
					`service_type_id` = '".$serviceType."' , 
					`total_service_contacts`  = '".$totalServiceContacts."', 
					`contact_by_person` ='".$contactByPerson."', 
					`contact_by_phone` ='".$contactByPhone."', 
					`contact_by_mail` = '".$contactByMail."', 
					`services` = '".$services."',	
					`service_hour_totals` = '".$serviceHourTotals."' 
				WHERE id = '".$isrId."';";
				
				$current_record = $isrId;
} else {
	
	#GET NEXT AVAILABLE AUTONUMBER
	$tablename 		= "monthlyISR";
	$next_increment 	= 0;
	$qShowStatus 		= "SHOW TABLE STATUS LIKE '$tablename'";
	$qShowStatusResult 	= mysql_query($qShowStatus) or die ( "Query failed:". mysql_error()."<br/>".$qShowStatus );
	$row = mysql_fetch_assoc($qShowStatusResult);
	$next_row = $row['Auto_increment'];

	//echo "next increment number: [$next_row]";
	//die();
	
	$query = "INSERT INTO `monthlyISR` ( `id` , 
											    `ir_id`, 
											   `consumer_id` , 
											   `case_note_month` , 
											   `case_note_year` , 
											   `case_note_coordinator` ,
											   `service_type_id` , 
											   `total_service_contacts` , 
											   `contact_by_person` , 
											   `contact_by_phone` , 
											   `contact_by_mail` , 
											   `services` ,
											   `service_hour_totals`, 
											   `entered_by` )
				VALUES ('".$next_row."', 
						    '".$irId."', 
						    '".$id."', 
						    '".$caseNoteMonth."', 
						   '".$caseNoteYear."', 
						   '".$caseNoteCoordinator."', 
						   '".$serviceType."', 
						   '".$totalServiceContacts."', 
						   '".$contactByPerson."', 
						   '".$contactByPhone."', 
						   '".$contactByMail."', 
						   '".$services."', 
						   '".$serviceHourTotals."', 
						   ".$userId.");";
						   
				$current_record = $next_row;
}

	#echo "new row id: [$next_row] <br/>";
	#echo "current record id: [$current_record] <br/>";

#here, we need to take care of entering the case service totals
#based on the amount of hours spent on each category

##THIS IF CONDITION IS NOT THE SHIT! WHAT THE HELL?
##WE ARE ENTERING AN ID FOR A NEW INSERT RECORD, BUT THE NEW INSERT ID
##IS NOT MAKING IT HERE
if(mysql_query($query)) {
		
	#echo "current record # after monthlyisr table query: [$current_record] <br/>";
	
	/*
	$misrIdquery = "SELECT id FROM monthlyISR where id = ".$isrId;
	$misrIdrow = mysql_fetch_array(mysql_query($misrIdquery));
	*/
	
	//$misrId = $misrIdrow["id"];
         
	$misrId = $current_record;	 
		 
	###
	#echo "MisrId Service Value AFTER data entered in MISR table : ".$misrId."<br />";
	
	### DEBUGGED TO HERE
	$categoryQuery = "select id from lst_service_category";
	$categoryResult = mysql_query($categoryQuery);
	
	while($categoryRow = mysql_fetch_array($categoryResult)) {
			$categoryId = $categoryRow["id"];
			$category = $_POST[$categoryId."_category"];
			$categoryHours = $_POST[$categoryId."_hours"];
			
			
			if($category) {
			        ###
				#echo "Category: ".$category." Hours: ".$categoryHours."<br/>";
				#die();
			
				$misr_service_query = "SELECT id 
										   FROM monthlyISR_service 
									           WHERE monthlyISR_id = '".$misrId."' 
									           AND service_category_id = '".$categoryId."'";
			//echo "<br/>Misr_service_query: ".$misr_service_query."<br/>";
			
				$misr_result = mysql_query($misr_service_query);
				
				
				if($misr_row = mysql_fetch_array($misr_result)){
					
					//echo "<h1>We are going to run an UPDATE </h1>";
					
					$misr_insert = "UPDATE monthlyISR_service 
										 SET hours = '".$categoryHours."' 
										 WHERE id = ".$misr_row["id"];
				
					//mysql_query($misr_update);
				
				}else{
					
					//echo "<h1>We are going to run an INSERT </h1>";
					
					$misr_insert = "INSERT INTO monthlyISR_service (monthlyISR_id, 
					                                                service_category_id, 
																	             hours) 
							           VALUES ('".$misrId."', 
									             '".$categoryId."', 
												     '".$categoryHours."')";
				
					//mysql_query($misr_insert);
					
					//echo "MisrId Service Value inside initial insert query: ".$misrId;
				}
				
				//now insert the match into our services with hours worked into our table
				
				#echo "MisrId Service Value before hitting services table: ".$misrId."<br />";
				
				if(mysql_query($misr_insert)) {
						### uncomment this line only to debug
						//	echo "<br/>Success<br/>".$misr_insert;
				} else {
						### uncomment this line only to debug
						//	echo "<br/>Error<br/>".$misr_insert;
				}
		}
	}

	
	//echo "Success <br/>".$query;
   header("Location:../admin.php?action=cieedit&id=".$id."&Status=Your Case Note Information Was Submitted Successfully");
   exit();

 } else {
	 
	echo "User:".$userId;
	echo "Failure <br/>".$query;
        die('Could not connect: ' . mysql_error());
	header("Location:../admin.php?action=cieedit&id=".$id."&Error=Unable to process this case note due to a system error.  Please contact system administrator.");
   exit();
}
?>
